package cookie_test;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/10/9 15:05
 * @Description: 返回用户最后一次登录的时间
 */
@WebServlet(name = "lastLoginTime", urlPatterns = {"/lastLoginTime"})
public class LastLoginTimeServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
    // 1. 当用户请求过来的时候，如何读取用户的Cookie
    // 2. 如何去给用户添加Cookie信息

    /**
     * 从请求头中获取用户的Cookie信息
     */

    response.getWriter().println("cookie in request");
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (Cookie ck : cookies) {
        response.getWriter().println(ck.getName() + "=" + ck.getValue());
      }
    }

    /**
     * Cookie以Key=value的形式出现，
     */
    LocalDateTime now = LocalDateTime.now();
    // cookie中的不能出现一些特殊的符号
    String date = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    Cookie c1 = new Cookie("t", date);
    Cookie c2 = new Cookie("b", "hello-world");
    c1.setMaxAge(30);   // 30s
    c2.setMaxAge(3000); // 50m

    // 设置路径
    // localhost:8080/
    // localhost:8080/exit
    c1.setPath("/");
    // 给响应添加Cookie信息
    response.addCookie(c1);
    response.addCookie(c2);
    response.setHeader("Content-Type", "text/html;charset=uft-8");
    response.getWriter().println("cookie update : " + date);
  }
}
